package com.incar.chuxing.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.incar.chuxing.BuildConfig;
import com.incar.chuxing.R;
import com.incar.chuxing.api.JsApiNewUser;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.base.BaseActivity;
import com.incar.chuxing.bean.AliAuthEvent;
import com.incar.chuxing.bean.ForeBackGroundEvent;
import com.incar.chuxing.bean.WebPaySuccessEvent;
import com.incar.chuxing.bean.WxAuthEvent;
import com.incar.chuxing.bean.ZhiMaEvent;
import com.incar.chuxing.utils.AppManager;
import com.incar.chuxing.utils.Dialogs.ChooseAvatarDialog;
import com.incar.chuxing.utils.IntentKey;
import com.incar.chuxing.utils.Logger;
import com.incar.chuxing.utils.RxBus;
import com.incar.chuxing.widget.WebViewProgressBar;
import com.linchaolong.android.imagepicker.ImagePicker;
import com.linchaolong.android.imagepicker.cropper.CropImage;
import com.linchaolong.android.imagepicker.cropper.CropImageView;
import com.umeng.message.PushAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import wendu.dsbridge.DWebView;
import wendu.dsbridge.OnReturnValue;

public class WebViewNewUserActivity extends BaseActivity {
    @BindView(R.id.title_back)
    public ImageView titleBack;
    @BindView(R.id.dWebView)
    DWebView dWebView;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.title_name)
    TextView titleName;
    @BindView(R.id.title_tv_more)
    public TextView titleTvMore;
    private ImagePicker imagePicker;
    private String url;
    private Context mContext = this;
    private String startUrl;
    private WebViewProgressBar webViewProgressBar;
    public PushAgent mPushAgent;
    public boolean forbidBackPresses = false;
    private Disposable disposable;

    @Override
    public int getLayoutId() {
        return R.layout.activity_web;
    }

    public void setTitle(String name) {
        titleName.setText(name);
    }

    public void setRightTitle(String name) {
        titleTvMore.setVisibility(View.VISIBLE);
        titleTvMore.setText(name);
    }

    public void setRightTitleColor(int color) {
        titleTvMore.setTextColor(color);
    }

    @Override
    public void initView() {

        EventBus.getDefault().register(this);
        mPushAgent = PushAgent.getInstance(this);
        mPushAgent.onAppStart();
        Intent intent = getIntent();
        imagePicker = new ImagePicker();
        //title = intent.getStringExtra(IntentKey.INTENT_WEBVIEW_TITLE);
        url = intent.getStringExtra(IntentKey.INTENT_WEBVIEW_URL);
        Logger.d("webview_url", url);
        syncCookie(url);
        webViewProgressBar = new WebViewProgressBar(progressBar);
        dWebView.setWebChromeClient(mWebChromeClient);
        dWebView.setWebViewClient(mWebViewClient);
        dWebView.getSettings().setSupportMultipleWindows(false);
        dWebView.getSettings().setAppCacheEnabled(false);
        dWebView.getSettings().setTextZoom(100);
        dWebView.getSettings().setGeolocationEnabled(true);
        dWebView.getSettings().setUserAgentString(dWebView.getSettings().getUserAgentString() + "appVersion=" + ((MyApplication) getApplication()).getAppVersion());
        dWebView.addJavascriptObject(new JsApiNewUser(mContext, WebViewNewUserActivity.this, imagePicker), null);
        if (BuildConfig.DEBUG) {
            dWebView.setWebContentsDebuggingEnabled(true);
        }
        dWebView.loadUrl(url);
        disposable = RxBus.getInstance().toObservable(ForeBackGroundEvent.class).subscribe(new Consumer<ForeBackGroundEvent>() {
            @Override
            public void accept(ForeBackGroundEvent foreBackGroundEvent) throws Exception {
                String h5Method = foreBackGroundEvent.isForeGround ? "NATIVE_APP_GO_FOREGROUND" : "NATIVE_APP_GO_BACKGROUND";

                dWebView.callHandler(h5Method, new Object[]{}, new OnReturnValue<String>() {
                    @Override
                    public void onValue(String retValue) {
                        Logger.d("jsbridge", h5Method + retValue);
                    }
                });
            }
        });
    }

    //违章支付后的回调（所有支付方式都回调）
    @Subscribe
    public void onPayResult(WebPaySuccessEvent event) {
        Logger.d("jsbridge", "pay success" + event.isPaySuccess);
        dWebView.callHandler("DDWEBVIEW_PAY_FINISH", new Object[]{event.isPaySuccess == 0 ? 1 : 2}, new OnReturnValue<Integer>() {
            @Override
            public void onValue(Integer retValue) {
                Logger.d("jsbridge", "pay success from js");
            }
        });
    }

    //违章支付后的回调（所有支付方式都回调）
    @Subscribe
    public void onZhiMaResult(ZhiMaEvent event) {
        Logger.d("jsbridge", "zhima success");
        dWebView.hasJavascriptMethod("DDWEBVIEW_ZM_IDENTIFICATION_FINISH", new OnReturnValue<Boolean>() {
            @Override
            public void onValue(Boolean retValue) {
                Logger.d("jsbridge", retValue + "intent");
                if (retValue) {
                    dWebView.callHandler("DDWEBVIEW_ZM_IDENTIFICATION_FINISH", new Object[]{}, new OnReturnValue<String>() {
                        @Override
                        public void onValue(String retValue) {
                            Logger.d("jsridge", "intentresult" + retValue);
                        }
                    });
                } else {
                    startActivity(new Intent(mContext, MainActivity.class));
                }
            }
        });
    }


    //支付宝登录结果
    @Subscribe
    public void onAliAuthResult(AliAuthEvent event) {
        Logger.d("jsBridge", "pay success");
        dWebView.callHandler("ALIPAY_AUTHORIZE_CALLBACK", new Object[]{event.result}, new OnReturnValue<Integer>() {
            @Override
            public void onValue(Integer retValue) {
                Logger.d("jsBridge", "aliAuth success from js");
            }
        });
    }

    //微信登录结果
    @Subscribe
    public void onWxAuthResult(WxAuthEvent event) {
        Logger.d("jsBridge", "pay success");
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("code", event.autoCode);
            jsonObject.put("errCode", event.resultCode);
            jsonObject.put("state", event.state);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        dWebView.callHandler("WX_AUTHORIZE_CALLBACK", new Object[]{jsonObject}, new OnReturnValue<Integer>() {
            @Override
            public void onValue(Integer retValue) {
                Logger.d("jsBridge", "wxAuth success from js");
            }
        });
    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            syncCookie(url);
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            startUrl = url;
            if (webViewProgressBar != null) {
                webViewProgressBar.onProgressStart();
            }

        }

    };
    private ValueCallback<Uri[]> mUploadCallback;
    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (webViewProgressBar != null) {
                webViewProgressBar.onProgressChange(newProgress);
            }
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
            mUploadCallback = filePathCallback;
            choosePic();
            return true;
        }
    };

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Logger.d("jsbridge", "intent" + intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Logger.d("jsbridge", "resume");
        dWebView.hasJavascriptMethod("DDWEBVIEW_VIEW_REFRESH", new OnReturnValue<Boolean>() {
            @Override
            public void onValue(Boolean retValue) {
                Logger.d("jsbridge", retValue + "DDWEBVIEW_VIEW_REFRESH");
                if (retValue) {
                    dWebView.callHandler("DDWEBVIEW_VIEW_REFRESH", new Object[]{}, new OnReturnValue<String>() {
                        @Override
                        public void onValue(String retValue) {
                            Logger.d("jsbridge", "DDWEBVIEW_VIEW_REFRESH" + retValue);
                        }
                    });
                } else {

                }
            }
        });
        dWebView.hasJavascriptMethod("NATIVE_VIEW_DID_APPEAR", new OnReturnValue<Boolean>() {
            @Override
            public void onValue(Boolean retValue) {
                Logger.d("jsbridge", retValue + "NATIVE_VIEW_DID_APPEAR");
                if (retValue) {
                    dWebView.callHandler("NATIVE_VIEW_DID_APPEAR", new Object[]{}, new OnReturnValue<String>() {
                        @Override
                        public void onValue(String retValue) {
                            Logger.d("jsbridge", "NATIVE_VIEW_DID_APPEAR" + retValue);
                        }
                    });
                } else {

                }
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        dismissLoadingDialog();
        dWebView.hasJavascriptMethod("NATIVE_VIEW_DID_DISAPPEAR", new OnReturnValue<Boolean>() {
            @Override
            public void onValue(Boolean retValue) {
                Logger.d("jsbridge", retValue + "NATIVE_VIEW_DID_DISAPPEAR");
                if (retValue) {
                    dWebView.callHandler("NATIVE_VIEW_DID_DISAPPEAR", new Object[]{}, new OnReturnValue<String>() {
                        @Override
                        public void onValue(String retValue) {
                            Logger.d("jsbridge", "NATIVE_VIEW_DID_DISAPPEAR" + retValue);
                        }
                    });
                } else {

                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        imagePicker.onActivityResult(this, requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        imagePicker.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @Override
    public void onBackPressed() {
        if (forbidBackPresses) {
            return;
        }
        dWebView.evaluateJavascript("window.dsBridge", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String s) {
                Logger.d("jsbridge", s + "NAVI222");
                if (!s.equals("null")) {
                    dWebView.hasJavascriptMethod("DDWEBVIEW_NAV_BACK", new OnReturnValue<Boolean>() {
                        @Override
                        public void onValue(Boolean retValue) {
                            Logger.d("jsbridge", retValue + "NAVI");
                            if (retValue) {
                                dWebView.callHandler("DDWEBVIEW_NAV_BACK", new Object[]{}, new OnReturnValue<String>() {
                                    @Override
                                    public void onValue(String retValue) {
                                        Logger.d("jsbridge", "NAVIRESULT" + retValue);
                                        if ("1".equals(retValue)) {

                                        } else {
                                            Intent intent = new Intent(mContext, MainActivity.class);
                                            intent.putExtra("jumpCode", 1);
                                            mContext.startActivity(intent);
                                        }
                                    }
                                });
                            } else {
                                if (!dWebView.canGoBack()) {
                                    Intent intent = new Intent(mContext, MainActivity.class);
                                    intent.putExtra("jumpCode", 1);
                                    mContext.startActivity(intent);
                                } else {
                                    dWebView.goBack();
                                }
                            }
                        }
                    });
                } else {
                    if (!dWebView.canGoBack()) {
                        AppManager.getAppManager().finishActivity();
                    } else {
                        dWebView.goBack();
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        if (webViewProgressBar != null) {
            webViewProgressBar.destroy();
            webViewProgressBar = null;
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (disposable != null) {
            disposable.dispose();
        }
        super.onDestroy();
    }


    @OnClick({R.id.title_back, R.id.title_tv_more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                onBackPressed();
                break;
            case R.id.title_tv_more:
                break;
        }
    }

    public boolean syncCookie(String url) {
        try {
            CookieManager cookieManager = CookieManager.getInstance();
            Map<String, String> requestMap = ((MyApplication) getApplication()).getCookieMap();
            for (String mapKey : requestMap.keySet()) {
                cookieManager.setCookie(url, mapKey + "=" + requestMap.get(mapKey));
            }
            String newCookie = cookieManager.getCookie(url);
            Logger.d("webview_cookies", url + "HHH" + newCookie);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(mContext);
                cookieSyncManager.sync();
            }
            return null != newCookie && !TextUtils.isEmpty(newCookie);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    private void choosePic() {
        //跳转图片选择
        final ChooseAvatarDialog chooseAvatarDialog = new ChooseAvatarDialog(mContext);
        chooseAvatarDialog.setOnItemClickListener(new ChooseAvatarDialog.OnItemClickListener() {
            @Override
            public void onClickItem(int position) {
                ImagePicker.Callback callback = new ImagePicker.Callback() {
                    // 选择图片回调
                    @Override
                    public void onPickImage(Uri imageUri) {


                    }

                    // 裁剪图片回调
                    @Override
                    public void onCropImage(Uri imageUri) {
                        mUploadCallback.onReceiveValue(new Uri[]{imageUri});
                        mUploadCallback = null;
                        chooseAvatarDialog.dismiss();
                    }

                    // 自定义裁剪配置
                    @Override
                    public void cropConfig(CropImage.ActivityBuilder builder) {
                        builder
                                // 是否启动多点触摸
                                .setMultiTouchEnabled(false)
                                // 设置网格显示模式
                                .setGuidelines(CropImageView.Guidelines.ON_TOUCH)
                                // 圆形/矩形
                                .setCropShape(CropImageView.CropShape.RECTANGLE)
                                // 调整裁剪后的图片最终大小
                                .setRequestedSize(400, 400)
                                // 宽高比
                                .setAspectRatio(1, 1);
                    }

                    // 用户拒绝授权回调
                    @Override
                    public void onPermissionDenied(int requestCode, String[] permissions, int[] grantResults) {
                    }
                };
                if (position == 0) {
                    imagePicker.startCamera((WebViewActivity) mContext, callback);
                } else if (position == 1) {
                    imagePicker.startGallery((WebViewActivity) mContext, callback);
                }
            }
        });

        chooseAvatarDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (mUploadCallback != null) {
                    mUploadCallback.onReceiveValue(null);
                }
            }
        });

        chooseAvatarDialog.show();
    }
}
